package com.support.widget.network;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.support.widget.ViewApplication;
import com.support.widget.util.FileUtils;
import com.support.widget.util.ImageUtils;
import com.support.widget.util.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.FileNameMap;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author zhenglei
 * @version 0.0.1
 * @since 2016/2/16
 */
@SuppressWarnings("rawtypes")
public class OkHttpClientManager {
    public static final int SUCCESS = 200;
    private static OkHttpClientManager mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mDelivery;
    private Gson mGson;
    private PersistentCookieStore cookieStore;

    public final static int CONNECT_TIMEOUT = 10;
    public final static int READ_TIMEOUT = 10;
    public final static int WRITE_TIMEOUT = 30;

    private OkHttpClientManager() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
        cookieStore = new PersistentCookieStore(ViewApplication.getInstance().getApplicationContext());
        mOkHttpClient.setCookieHandler(new CookieManager(cookieStore, CookiePolicy.ACCEPT_ALL));
        mDelivery = new Handler(Looper.getMainLooper());
        mGson = new Gson();
    }

    public OkHttpClient getmOkHttpClient() {
        return mOkHttpClient;
    }

    public List<HttpCookie> getHttpCookies(URI uri) {
        return cookieStore.get(uri);
    }

    public static OkHttpClientManager getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpClientManager.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpClientManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 同步的Get请求
     *
     * @param url
     * @return Response
     */
    private Response _getAsyn(String url) throws IOException {
        final Request request = new Request.Builder().url(url).build();
        Call call = mOkHttpClient.newCall(request);
        Response execute = call.execute();
        return execute;
    }

    /**
     * 同步的Get请求
     *
     * @param url
     * @return 字符串
     */
    private String _getAsString(String url) throws IOException {
        Response execute = _getAsyn(url);
        return execute.body().string();
    }

    /**
     * 异步的get请求
     *
     * @param url
     * @param callback
     */
    private void _getAsyn(String url, final ResultCallback callback) {
        final Request request = new Request.Builder().url(url).build();
        deliveryResult(callback, request);
    }

    /**
     * 同步的Post请求
     *
     * @param url
     * @param params post的参数
     * @return
     */
    private Response _post(String url, List<Param> params, String className) throws IOException {
        Request request = buildPostRequest(url, params, className);
        Response response = mOkHttpClient.newCall(request).execute();
        return response;
    }

    /**
     * 同步的Post请求
     *
     * @param url
     * @param params post的参数
     * @return 字符串
     */
    private String _postAsString(String url, List<Param> params, String className) throws IOException {
        Response response = _post(url, params, className);
        return response.body().string();
    }

    /**
     * 异步的post请求
     *
     * @param url
     * @param callback
     * @param params
     */
    private void _postAsyn(String url, final ResultCallback callback, List<Param> params, String className) {
        Request request = buildPostRequest(url, params, className);
        deliveryResult(callback, request);
    }

    /**
     * 异步的post请求
     *
     * @param url
     * @param callback
     * @param params
     */
    private void _postAsyn(String url, final ResultCallback callback, Map<String, String> params, String className) {
        List<Param> paramsArr = map2Params(params);
        Request request = buildPostRequest(url, paramsArr, className);
        deliveryResult(callback, request);
    }

    /**
     * 同步基于post的文件上传
     *
     * @param params
     * @return
     */
    private Response _post(String url, File[] files, String[] fileKeys, List<Param> params) throws IOException {
        Request request = buildMultipartFormRequest(url, files, fileKeys, params);
        return mOkHttpClient.newCall(request).execute();
    }

    private Response _post(String url, File file, String fileKey) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
        return mOkHttpClient.newCall(request).execute();
    }

    private Response _post(String url, File file, String fileKey, List<Param> params) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
        return mOkHttpClient.newCall(request).execute();
    }

    /**
     * 异步基于post的文件上传
     *
     * @param url
     * @param callback
     * @param files
     * @param fileKeys
     * @throws IOException
     */
    private void _postAsyn(String url, ResultCallback callback, File[] files, String[] fileKeys, List<Param> params) throws IOException {
        Request request = buildMultipartFormRequest(url, files, fileKeys, params);
        deliveryResult(callback, request);
    }

    /**
     * 异步基于post的文件上传，单文件不带参数上传
     *
     * @param url
     * @param callback
     * @param file
     * @param fileKey
     * @throws IOException
     */
    private void _postAsyn(String url, ResultCallback callback, File file, String fileKey) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
        deliveryResult(callback, request);
    }

    /**
     * 异步基于post的文件上传，单文件且携带其他form参数上传
     *
     * @param url
     * @param callback
     * @param file
     * @param fileKey
     * @param params
     * @throws IOException
     */
    private void _postAsyn(String url, ResultCallback callback, File file, String fileKey, List<Param> params) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
        deliveryResult(callback, request);
    }

    /**
     * 异步下载文件
     *
     * @param url
     * @param destFileDir
     *            本地文件存储的文件夹
     * @param callback
     */
    /**
     * 下载监听
     *
     * @param uIchangeListener
     */
    public void _downloadAsyn(final String url, final String destFileDir, final String fileName, final ResultCallback callback, final UIchangeListener uIchangeListener) {
        final Request request = new Request.Builder().url(url).build();
        ProgressHelper.addProgressResponseListener(mOkHttpClient, new UIProgressResponseListener() {
            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                uIchangeListener.progressUpdate(bytesRead, contentLength, done);
            }
        }).newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Response response) throws IOException {

                int code = response.code();
                if (code != SUCCESS) {
                    LogUtil.e("response.code:" + code);
                    sendSuccessResultCallback(null, callback);
                    return;
                }
                File file = FileUtils.saveFile2Local(response, destFileDir, fileName);
                if (file == null) {
                    callback.onError("下载失败");
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                sendFailedStringCallback(null, callback);
            }
        });

    }

    public void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback) {
        final Request request = new Request.Builder().url(url).build();
        final Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(final Request request, final IOException e) {
                sendFailedStringCallback(null, callback);
            }

            @Override
            public void onResponse(Response response) {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(destFileDir, getFileName(url));
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    // 如果下载文件成功，第一个参数为文件的绝对路径
                    sendSuccessResultCallback(file.getAbsolutePath(), callback);
                } catch (IOException e) {
                    sendFailedStringCallback(e.getMessage(), callback);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }

            }
        });
    }

    private String getFileName(String path) {
        int separatorIndex = path.lastIndexOf("/");
        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
    }

    /**
     * 加载图片
     *
     * @param view
     * @param url
     * @throws IOException
     */
    private void _displayImage(final ImageView view, final String url, final int errorResId) {
        final Request request = new Request.Builder().url(url).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                setErrorResId(view, errorResId);
            }

            @Override
            public void onResponse(Response response) {
                InputStream is = null;
                try {
                    is = response.body().byteStream();
                    BitmapFactory.Options ops = new BitmapFactory.Options();
                    ops.inJustDecodeBounds = true;
                    BitmapFactory.decodeStream(is, null, ops);
                    int inSampleSize = ImageUtils.computeSampleSize(ops, -1, 200 * 200);
                    try {
                        is.reset();
                    } catch (IOException e) {
                        response = _getAsyn(url);
                        is = response.body().byteStream();
                    }

                    ops.inJustDecodeBounds = false;
                    ops.inSampleSize = inSampleSize;
                    final Bitmap bm = BitmapFactory.decodeStream(is, null, ops);
                    mDelivery.post(new Runnable() {
                        @Override
                        public void run() {
                            view.setImageBitmap(bm);
                        }
                    });
                } catch (Exception e) {
                    setErrorResId(view, errorResId);

                } finally {
                    if (is != null)
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }
        });

    }

    private void setErrorResId(final ImageView view, final int errorResId) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                view.setImageResource(errorResId);
            }
        });
    }

    // *************对外公布的方法************

    public static Response getAsyn(String url) throws IOException {
        return getInstance()._getAsyn(url);
    }

    public static String getAsString(String url) throws IOException {
        return getInstance()._getAsString(url);
    }

    public static void getAsyn(String url, ResultCallback callback) {
        getInstance()._getAsyn(url, callback);
    }

    public static Response post(String url, List<Param> params, String className) throws IOException {
        return getInstance()._post(url, params, className);
    }

    public static String postAsString(String url, List<Param> params, String className) throws IOException {
        return getInstance()._postAsString(url, params, className);
    }

    public static void postAsyn(String url, final ResultCallback callback, List<Param> params, String className) {
        getInstance()._postAsyn(url, callback, params, className);
    }

    public static void postAsyn(String url, final ResultCallback callback, Map<String, String> params, String className) {
        getInstance()._postAsyn(url, callback, params, className);
    }

    public static Response post(String url, File[] files, String[] fileKeys, List<Param> params) throws IOException {
        return getInstance()._post(url, files, fileKeys, params);
    }

    public static Response post(String url, File file, String fileKey) throws IOException {
        return getInstance()._post(url, file, fileKey);
    }

    public static Response post(String url, File file, String fileKey, List<Param> params) throws IOException {
        return getInstance()._post(url, file, fileKey, params);
    }

    public static void postAsyn(String url, ResultCallback callback, File[] files, String[] fileKeys, List<Param> params) throws IOException {
        getInstance()._postAsyn(url, callback, files, fileKeys, params);
    }

    public static void postAsyn(String url, ResultCallback callback, File file, String fileKey) throws IOException {
        getInstance()._postAsyn(url, callback, file, fileKey);
    }

    public static void postAsyn(String url, ResultCallback callback, File file, String fileKey, List<Param> params) throws IOException {
        getInstance()._postAsyn(url, callback, file, fileKey, params);
    }

    public static void displayImage(final ImageView view, String url, int errorResId) throws IOException {
        getInstance()._displayImage(view, url, errorResId);
    }

    public static void displayImage(final ImageView view, String url) {
        getInstance()._displayImage(view, url, -1);
    }

    // public static void downloadAsyn(String url, String destDir,
    // ResultCallback callback) {
    // getInstance()._downloadAsyn(url, destDir, callback);
    // }

    public static void downloadAsyn(String url, String destDir, String fileName, ResultCallback callback, UIchangeListener uIchangeListener) {
        getInstance()._downloadAsyn(url, destDir, fileName, callback, uIchangeListener);
    }

    public static void cancelAll() {
        getInstance().getmOkHttpClient().cancel(REQUEST_TAG);
        // map.clear();
    }

    public static void cancelAll(Object tag) {
        getInstance().getmOkHttpClient().cancel(tag);
        // map.clear();
    }

    /**
     * 清除OkHttpClientManager对象
     */
    public static void destroySession() {
        mInstance = null;
    }

    // ****************************

    // 记录请求次数
//	private int responseCount(Response response) {
//		int result = 1;
//		while ((response = response.priorResponse()) != null) {
//			result++;
//		}
//		return result;
//	}

    private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, List<Param> params) {
        params = validateParam(params);

        MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);

        for (Param param : params) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""), RequestBody.create(null, param.value));
        }
        if (files != null) {
            RequestBody fileBody = null;
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                String fileName = file.getName();
                fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
                // TODO 根据文件名设置contentType
                builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""), fileBody);
            }
        }

        RequestBody requestBody = builder.build();
        return new Request.Builder().url(url).post(requestBody).build();
    }

    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    private List<Param> validateParam(List<Param> params) {
        if (params == null)
            return new ArrayList<Param>();
        else
            return params;
    }

    @SuppressWarnings("unused")
    private List<Param> map2Params(Map<String, String> params) {
        if (params == null)
            return new ArrayList<Param>();
        int size = params.size();
        List<Param> res = new ArrayList<Param>();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        int i = 0;
        for (Map.Entry<String, String> entry : entries) {
            res.add(new Param(entry.getKey(), entry.getValue()));
        }
        return res;
    }

    @SuppressWarnings("unused")
    private static final String SESSION_KEY = "Set-Cookie";
    @SuppressWarnings("unused")
    private static final String mSessionKey = "JSESSIONID";

    @SuppressWarnings("unused")
    private Map<String, String> mSessions = new HashMap<String, String>();
    private static final int REQUEST_TAG = 0;

    private long post_start = 0;// 请求发起次序
    private long post_end = 0;// 请求结束次序

    private void deliveryResult(final ResultCallback callback, Request request) {
        LogUtil.i("-------------" + post_start + "----------------");
        LogUtil.i("-------------" + post_end + "----------------");
        post_start++;
        final Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(final Request request, final IOException e) {
                post_end++;
                callback.onFinish();
                cancelAll();
                sendFailedStringCallback(null, callback);
            }

            @Override
            public void onResponse(final Response response) {
                post_end++;
                callback.onFinish();
                try {
                    int code = response.code();
                    if (code != SUCCESS) {
                        LogUtil.e("response.code:" + code);
                        sendSuccessResultCallback(null, callback);
                        return;
                    }
                    final String string = response.body().string();
                    LogUtil.i(string);
                    String toGetData = toGetData(response, string, callback);
                    if (callback.mType == String.class) {
                        sendSuccessResultCallback(toGetData, callback);
                    } else {
                        Object o = mGson.fromJson(toGetData, callback.mType);
                        sendSuccessResultCallback(o, callback);
                    }
                } catch (IOException e) {
                    post_end++;
                    sendFailedStringCallback(e.getMessage(), callback);
                } catch (com.google.gson.JsonParseException e)// Json解析的错误
                {
                    post_end++;
                    sendFailedStringCallback("Json解析的错误", callback);
                }

            }
        });
    }

    public static final String ERROR = "网络不给力";

    private String toGetData(Response response, String string, OkHttpClientManager.ResultCallback callback) {
        try {
            JSONObject jsonObject = new JSONObject(string);
            String status = jsonObject.getString("code");

            if (status.startsWith("100000")) {
                return jsonObject.getString("data");
            } else {
                sendFailedStringCallback(jsonObject.getString("message"), callback);
                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

    private void sendFailedStringCallback(final String request, final ResultCallback callback) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null)
                    callback.onError(request);
            }
        });
    }

    private void sendSuccessResultCallback(final Object object, final ResultCallback callback) {

        mDelivery.post(new Runnable() {
            @SuppressWarnings("unchecked")
            @Override
            public void run() {
                if (callback != null) {
                    callback.onResponse(object);
                }
            }
        });
    }

    private Request buildPostRequest(String url, List<Param> params, String className) {
        if (params == null) {
            params = new ArrayList<Param>();
        }
        FormEncodingBuilder builder = new FormEncodingBuilder();
        StringBuffer b = new StringBuffer();
        for (Param param : params) {
            if (TextUtils.isEmpty(param.value)) {
                builder.add(param.key, "");
                b.append(param.key + "=" + "&");
            } else {
                builder.add(param.key, param.value);
                b.append(param.key + "=" + param.value + "&");
            }

        }
        builder.add("channel", "02");
        b.append("channel" + "=" + "02");
        RequestBody requestBody = builder.build();
        LogUtil.i("客户端请求体:" + requestBody.toString());
        LogUtil.i(url + "?" + b.toString());
//        if (!TextUtils.isEmpty(MyApp.getInstance().cookie)) {
//            // 网页登录
//            @SuppressWarnings("static-access")
//            String c = "sid" + "=" + MyApp.getInstance().cookie + ";domain=" + MyApp.getInstance().DOMAIN.split("//")[1];
//            LogUtil.i("客户端请求设置的cookie-----" + c);
//            return new Request.Builder().tag(className).url(url).header("Cookie", c).post(requestBody).build();
//        } else {
//            return new Request.Builder().tag(className).url(url).post(requestBody).build();
//        }
        return new Request.Builder().tag(className).url(url).post(requestBody).build();
    }

    //baseresponse<Bean>
    public static abstract class ResultCallback<T> {
        Type mType;

        public ResultCallback() {
            mType = getSuperclassTypeParameter(getClass());
        }

        static Type getSuperclassTypeParameter(Class<?> subclass) {
            Type superclass = subclass.getGenericSuperclass();
            if (superclass instanceof Class) {
                throw new RuntimeException("Missing type parameter.");
            }
            ParameterizedType parameterized = (ParameterizedType) superclass;
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }

        public abstract void onError(String message);

        public abstract void onResponse(T resp);

        public abstract void onFinish();
    }

    public interface UIchangeListener {
        void progressUpdate(long bytesWrite, long contentLength, boolean done);
    }

    public static class Param {
        public Param() {
        }

        public Param(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public String key;
        public String value;

        @Override
        public String toString() {
            return "{key:" + key + ", value:" + value + "}";
        }
    }

}